<template>
	<view>
		<view class="upload-img flex-ali-center">
			<block v-for="(item, index) in imageList" :key="index">
				<view class="img-item"
				:data-src="item"
				@tap="previewImage">
					<image :src="item" class="img-item-image" @longpress="deleteImg(index)" mode="widthFix"></image>
				</view>
			</block>
			<view class="img-upload-btn img-item flex-all-centen"
			@tap="chooseImage">
				<view class="icon-container">
					<view class="iconfont icon-xiangji"></view>
					<view>照片/拍照</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	var sourceType = [
		['camera'],
		['album'],
		['camera', 'album']
	]
	var sizeType = [
		['compressed'],
		['original'],
		['compressed', 'original']
	]
	export default {
		data() {
			return {
				imageList: [],
				sourceTypeIndex: 2,
				sourceType: ['拍照', '相册', '拍照或相册'],
				sizeTypeIndex: 2,
				sizeType: ['压缩', '原图', '压缩或原图'],
				countIndex: 8,
				count: [1, 2, 3, 4, 5, 6, 7, 8, 9]
			};
		},
		props:{
			imgList: {
				type:Array,
				default:function(){
					imgList:[]
				}
			},
			imgNum:{
				type:Number,
				default:9
			}
		},
		created(){
			setTimeout(res=>{
				if(this.imgList.length>0){
					this.imageList = this.imgList
				}
				
			},500)
		},
		
		methods:{
			chooseImage: async function() {
				// #ifdef APP-PLUS
				// TODO 选择相机或相册时 需要弹出actionsheet，目前无法获得是相机还是相册，在失败回调中处理
				if (this.sourceTypeIndex !== 2) {
					let status = await this.checkPermission();
					if (status !== 1) {
						return;
					}
				}
				// #endif
			
				if (this.imageList.length === this.imgNum) {
					let isContinue = await this.isFullImg();
					console.log("是否继续?", isContinue);
					if (!isContinue) {
						return;
					}
				}
				uni.chooseImage({
					sourceType: sourceType[this.sourceTypeIndex],
					sizeType: sizeType[this.sizeTypeIndex],
					count: this.imageList.length + this.count[this.countIndex] > this.imgNum ? this.imgNum - this.imageList.length : this.count[this.countIndex],
					success: (res) => {
						console.log(res)
						this.imageList = this.imageList.concat(res.tempFilePaths);
						this.$emit("getImgList",this.imageList)
					},
					fail: (err) => {
						// #ifdef APP-PLUS
						if (err['code'] && err.code !== 0 && this.sourceTypeIndex === 2) {
							this.checkPermission(err.code);
						}
						// #endif
						// #ifdef MP
						uni.getSetting({
							success: (res) => {
								let authStatus = false;
								switch (this.sourceTypeIndex) {
									case 0:
										authStatus = res.authSetting['scope.camera'];
										break;
									case 1:
										authStatus = res.authSetting['scope.album'];
										break;
									case 2:
										authStatus = res.authSetting['scope.album'] && res.authSetting['scope.camera'];
										break;
									default:
										break;
								}
								if (!authStatus) {
									uni.showModal({
										title: '授权失败',
										content: '校园趣事需要从您的相机或相册获取图片，请在设置界面打开相关权限',
										success: (res) => {
											if (res.confirm) {
												uni.openSetting()
											}
										}
									})
								}
							}
						})
						// #endif
					}
				})
			},
			isFullImg: function() {
				return new Promise((res) => {
					uni.showModal({
						content: `已经有${this.imgNum}张图片了,是否清空现有图片？`,
						success: (e) => {
							if (e.confirm) {
								this.imageList = [];
								res(true);
							} else {
								res(false)
							}
						},
						fail: () => {
							res(false)
						}
					})
				})
			},
			previewImage: function(e) {
				var current = e.currentTarget.dataset.src
				console.log(e)
				uni.previewImage({
					current: current,
					urls: this.imageList
				})
			},
			async checkPermission(code) {
				let type = code ? code - 1 : this.sourceTypeIndex;
				let status = permision.isIOS ? await permision.requestIOS(sourceType[type][0]) :
					await permision.requestAndroid(type === 0 ? 'android.permission.CAMERA' :
						'android.permission.READ_EXTERNAL_STORAGE');
			
				if (status === null || status === 1) {
					status = 1;
				} else {
					uni.showModal({
						content: "没有开启权限",
						confirmText: "设置",
						success: function(res) {
							if (res.confirm) {
								permision.gotoAppSetting();
							}
						}
					})
				}
			
				return status;
			},
			deleteImg(index){
				uni.showModal({
				    title: '提示',
				    content: '是否要删除图片',
					cancelColor:"#666",
					ConfirmColor:"#FF0000",
				    success:(res) =>{
				        if (res.confirm) {
				           this.imageList.splice(index,1)
						   this.$emit("getImgList",this.imageList);
				        } else if (res.cancel) {
				        }
				    }
				});
				
			}
		}
	}
</script>

<style lang="scss">
	.upload-img{
		margin: 10rpx;
		flex-wrap: wrap;
		.img-item{
			width: 200rpx;
			height: 200rpx;
			overflow: hidden;
			margin: 10rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			background-color: #2a2a00;
			box-shadow: 1rpx 1rpx 5rpx 1rpx rgba(0, 0, 0, .2);
			.img-item-image{
				width: 200rpx;
				// max-height: 200rpx;
			}
		}
		.img-upload-btn{
			background-color: #f2f2f2;
			.icon-container{
				text-align: center;
				font-size: 24rpx;
				color: #888888;
			}
		}
	}
</style>
